using dotnet_ef_admin.Src.Services;
using Microsoft.AspNetCore.Mvc;

namespace dotnet_ef_admin.Src.Controllers;

[Route("/api/v1/[controller]")] // 路由：api/v1/dicts
[ApiController] // 标记控制器为Api控制器
public class DictController(IDictService _dictService) : ControllerBase {
    /// <summary>
    /// 获取所有字典。
    /// </summary>
    /// <param name="dto">用于查询的DTO对象。</param>
    /// <returns>包含所有字典的列表。</returns>
    [HttpGet("page")]
    public async Task<ActionResult<GetAllDictsResult>> FindAll([FromQuery] FindAllDictsDto dto) {
        var dicts = await _dictService.FindAllAsync(dto);
        return Ok(dicts);
    }

    /// <summary>
    /// 获取指定ID的字典。
    /// </summary>
    /// <param name="id">字典的ID。</param>
    /// <returns>找到的字典实例。</returns>
    [HttpGet("{id}/form")]
    public async Task<ActionResult<DictEntryResult>> FindForm(int id) {
        var dict = await _dictService.FindFormAsync(id);
        if (dict == null) return NotFound();
        return Ok(dict);
    }

    /// <summary>
    /// 创建新的字典。
    /// </summary>
    /// <param name="dict">要创建的字典实例。</param>
    /// <returns>创建成功的字典实例。</returns>
    [HttpPost]
    public async Task<ActionResult<DictEntryResult>> Create(DictEntry dict) {
        var newDict = await _dictService.CreateAsync(dict);
        return Ok(newDict);
    }

    /// <summary>
    /// 更新指定ID的字典。
    /// </summary>
    /// <param name="id">字典的ID。</param>
    /// <param name="dict">要更新的字典实例。</param>
    /// <returns>更新后的字典实例。</returns>
    [HttpPut("{id}")]
    public async Task<ActionResult<DictEntryResult>> Update(int id, DictEntryResult dict) {
        if (id != dict.Id) return BadRequest();

        var updated = await _dictService.UpdateAsync(id, dict);
        return Ok(updated);
    }

    /// <summary>
    /// 删除多个字典。
    /// </summary>
    /// <param name="ids">一个或多个字典的ID，以逗号分隔。</param>
    /// <returns>删除操作的结果。</returns>
    [HttpDelete("{ids}")]
    public async Task<IActionResult> DeleteMany([FromRoute] string ids) {
        // 将传入的字符串ids（比如"2,3"）转换为整数数组
        var idArray = ids.Split(',').Select(int.Parse).ToArray();

        await _dictService.DeleteManyAsync(idArray);

        return Ok("删除成功");
    }
}